<template>
	<div style="padding: 10vh 10rpx;">
		<div style="border: 1px solid #e2e2e2; margin: 5rpx; box-shadow: 0 0 30rpx #d4d4d4; padding: 40rpx;">
			<div style="margin-bottom: 20rpx">手机号</div>
			<input type="text" v-model="loginParams.phone" style="border: 1px solid #cecece; text-align: left;"
				maxlength="11" />
			<div style="display: flex; line-height: 50rpx; margin: 20rpx 0;">
				<input type="text" v-model="loginParams.code"
					style="border: 1px solid #cecece; width: 300rpx; text-align: left;" maxlength="6" />
				<div style="margin-left: 50rpx;">
					<span v-if="remainSeconds > 0" style="color: gray">发送验证码{{ remainSeconds }}s</span>
					<span v-else @tap="sendPhoneVerifyCode()">发送验证码</span>
				</div>
			</div>
			<button class="btn" @tap="loginByPhone()">登录</button>
		</div>
		<div style="margin-top: 50rpx; display: ; justify-content: center;">
			<div style="text-align:center;">第三方授权登录</div>
			<hr>
			<div style="text-align:center;">
				<image src="../static/weixin-login.png" style="width:100rpx;height:100rpx;" @tap="weiXinLogin()"
					mode=""></image>
				<image src="../static/qq-login.png" style="width:100rpx;height:100rpx;" @tap="tencentLogin()" mode="">
				</image>
			</div>
		</div>

		<div v-if="flagShowDialog" class="mask"></div>
		<div v-if="flagShowDialog" class="dialog">
			<div>请使用微信扫码</div>
			<image :src="qrcodeImg" mode="" style="width:300rpx; height:300rpx; border:1px solid gray;"></image>
			<div><button type="warn" size="mini" @tap="flagShowDialog = false">关闭</button></div>
		</div>
	</div>
</template>

<script>
	import {
		mapMutations
	} from 'vuex';
	import * as userApi from '@/api/userApi.js';
	export default {
		data() {
			return {
				flagShowDialog: false,
				qrcodeImg: '', // 微信扫码授权登录二维码
				loginParams: {
					phone: '',
					code: ''
				},
				remainSeconds: 0, // 验证码倒计时
				state: '', // 用来获取token的临时字符串
				timer: null
			};
		},
		onLoad({
			token
		}) {
			if (token) uni.setStorageSync('token', token);
		},
		mounted() {
			this.handlerLocalToken();
		},
		destroyed() {
			clearInterval(this.timer);
		},
		methods: {
			...mapMutations(['setUserInfo']),
			goBackPage() {
				let pages = getCurrentPages(); // 当前页面
				if (pages == null || pages.length <= 1) {
					// 如果第一次打开的是登录页或者是测试页面就重载到主页
					uni.reLaunch({
						url: '/pages/userCenter/index'
					});
				} else {
					// 返回上一个页面
					uni.navigateBack({
						delta: 1
					});
				}
			},
			// 通过本地缓存的token去登录
			handlerLocalToken() {
				let token = uni.getStorageSync('token');
				console.log('[localStorage] token=' + token);
				if (token) {
					userApi.getUserInfo({
						success: result => {
							console.log('[通过token登录]');
							this.setUserInfo(result.data);
							this.goBackPage();
						}
					});
				}
			},
			// 微信openid登录
			weiXinLogin() {
				let that = this;
				let platform = uni.getSystemInfoSync().platform; // android|ios|windows|mac|devtools
				if (platform == 'windows' || platform == 'mac') {
					// 微信扫码登录
					userApi.loginByWeixin({
						type: 1,
						success: res => {
							this.flagShowDialog = true;
							this.state = res.data.state;
							this.qrcodeImg = res.data.qrcodeImg;
							// 开启定时器：轮询电脑端微信扫码登录授权结果
							clearInterval(this.timer);
							this.timer = setInterval(() => {
								userApi.getTokenByState({
									state: this.state,
									success: result => {
										if (result.data) {
											uni.setStorageSync('token', result.data);
											this.handlerLocalToken();
										}
									}
								});
							}, 3000);
						}
					});
				} else {
					// #ifdef H5
					// 微信网页跳转授权
					userApi.loginByWeixin({
						type: 2,
						success: res => {
							window.open(res.data);
						}
					});
					// #endif

					// #ifdef MP-WEIXIN
					// 微信小程序直接授权登录
					uni.login({
						provider: 'weixin',
						success: wxRes => {
							// eg: {code: "073BdF1w3us1mV2SRk1w3MDxpH3BdF1z", errMsg: "login:ok"}
							console.log('微信登录成功 获取到的code=', wxRes.code);
							userApi.loginByWeixin({
								type: 3,
								code: wxRes.code,
								success: res => {
									uni.setStorageSync('token', res.data);
									this.handlerLocalToken();
								}
							});
						}
					});
					// #endif
				}
			},
			// 发送手机验证码
			sendPhoneVerifyCode() {
				if (!/^1\d{10}$/.test(this.loginParams.phone)) {
					this.$msg('请输入正确的11位手机号');
					return;
				}
				userApi.sendPhoneVerifyCode({
					phone: this.loginParams.phone,
					success: res => {
						this.$msg(res.msg);
						if (res.data > 0) {
							this.startCountdown(res.data);
						}
					}
				});
			},
			// 开始倒计时
			startCountdown(remainSeconds) {
				if (remainSeconds <= 0) return;
				let that = this;
				that.remainSeconds = remainSeconds;
				let timer = setInterval(() => {
					that.remainSeconds -= 1;
					if (that.remainSeconds <= 0) clearInterval(timer);
				}, 1000);
			},
			// 手机验证码登录
			loginByPhone() {
				if (this.loginParams.code.length < 6) {
					this.$msg('请输入6位验证码');
					return;
				}
				userApi.loginByPhone({
					phone: this.loginParams.phone,
					code: this.loginParams.code,
					success: res => {
						uni.setStorageSync('token', res.data);
						this.handlerLocalToken();
					}
				});
			},
			// 腾讯授权登录
			tencentLogin() {
				let url = this.$config.baseUrl + '/tencentAuth/' + uni.getStorageSync('shopId')
				window.open(url + "?rand=" + new Date().getTime()) // 防止走缓存
			},
		}
	};
</script>

<style>
	.btn {
		margin: 10rpx 0;
		height: 70rpx;
		line-height: 70rpx;
	}

	/* 微信授权二维码弹窗 */
	.dialog {
		position: absolute;
		top: 20vh;
		left: 0;
		width: calc(100% - 60rpx);
		z-index: 100;
		background-color: white;
		padding: 30rpx;
		line-height: 60rpx;
		color: #5a5a5a;
		text-align: center;
	}

	/* 弹窗遮罩 */
	.mask {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 90;
		background-color: black;
		opacity: 0.4;
	}
</style>
